package com.wande.dataplatform.filecollection.source.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wande.common.core.exception.ServiceException;
import com.wande.dataplatform.filecollection.common.constant.FileCollectionConstants;
import com.wande.dataplatform.filecollection.source.IFileSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

/**
 * HTTP文件来源实现
 *
 * @author wande
 */
@Slf4j
@Component
public class HttpFileSource implements IFileSource {

    @Override
    public String getSupportedSourceType() {
        return FileCollectionConstants.SourceType.HTTP;
    }

    @Override
    public List<String> listFiles(String config) {
        // HTTP方式通常是直接指定URL，不支持列表
        JSONObject configJson = JSONUtil.parseObj(config);
        String url = configJson.getStr("url");
        return Collections.singletonList(url);
    }

    @Override
    public InputStream getFileStream(String config, String filePath) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String url = filePath;
        String method = configJson.getStr("method", "GET");
        JSONObject headers = configJson.getJSONObject("headers");

        try {
            HttpRequest request = "POST".equalsIgnoreCase(method) 
                ? HttpRequest.post(url) 
                : HttpRequest.get(url);

            // 添加请求头
            if (headers != null) {
                headers.forEach((key, value) -> request.header(key, String.valueOf(value)));
            }

            HttpResponse response = request.execute();
            if (!response.isOk()) {
                throw new ServiceException("HTTP请求失败: " + response.getStatus());
            }

            byte[] bytes = response.bodyBytes();
            log.info("下载HTTP文件成功, url={}, size={}", url, bytes.length);
            return new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            throw new ServiceException("下载HTTP文件失败: " + url);
        }
    }

    @Override
    public long getFileSize(String config, String filePath) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String url = filePath;
        JSONObject headers = configJson.getJSONObject("headers");

        try {
            HttpRequest request = HttpRequest.head(url);
            
            // 添加请求头
            if (headers != null) {
                headers.forEach((key, value) -> request.header(key, String.valueOf(value)));
            }

            HttpResponse response = request.execute();
            String contentLength = response.header("Content-Length");
            if (contentLength != null) {
                return Long.parseLong(contentLength);
            }
            return 0L;
        } catch (Exception e) {
            log.warn("获取HTTP文件大小失败: {}", url, e);
            return 0L;
        }
    }

    @Override
    public boolean testConnection(String config) {
        try {
            JSONObject configJson = JSONUtil.parseObj(config);
            String url = configJson.getStr("url");
            JSONObject headers = configJson.getJSONObject("headers");

            HttpRequest request = HttpRequest.head(url);
            
            // 添加请求头
            if (headers != null) {
                headers.forEach((key, value) -> request.header(key, String.valueOf(value)));
            }

            HttpResponse response = request.execute();
            return response.isOk();
        } catch (Exception e) {
            log.error("测试HTTP连接失败", e);
            return false;
        }
    }
}
